//
//  CZLoopView.m
//  UI-01-图片轮播
//
//  Created by Apple on 16/3/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "CZLoopView.h"
#import "CZLoopViewLayout.h"
#import "CZLoopViewCell.h"

NSString *const CZLoopViewCellId = @"CZLoopViewCellId";

@interface CZLoopView() <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) NSArray <NSURL *> *urls;

@end

// `独立`的处理轮播器相关的所有代码逻辑！
@implementation CZLoopView {
    
}

- (instancetype)initWithURLs:(NSArray <NSURL *> *)urls {
    // UICollectionViewFlowLayout
    self = [super initWithFrame:CGRectZero collectionViewLayout:[[CZLoopViewLayout alloc] init]];
    if (self) {
        self.urls = urls;
        
        self.dataSource = self;
        self.delegate = self;
        
        [self registerClass:[CZLoopViewCell class] forCellWithReuseIdentifier:CZLoopViewCellId];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.urls.count inSection:0];
            
            // 滚动位置！
            [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        });
    }
    return self;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.urls.count * 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CZLoopViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CZLoopViewCellId forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
    
    cell.url = self.urls[indexPath.item % self.urls.count];
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // 1. 获取当前停止的页面
    NSInteger offset = scrollView.contentOffset.x / scrollView.bounds.size.width;
    
    
    // 2. 第0页，调转到，第1组的第0页
    // 最后一页，跳转到第0组的最后一页
    if (offset == 0 || offset == ([self numberOfItemsInSection:0] - 1)) {
        NSLog(@"%zd", offset);
        
        // 第 0 页
        if (offset == 0) {
            offset = self.urls.count;
        } else {
            offset = self.urls.count - 1;
        }
        
        // 重新调整 contentOffset
        scrollView.contentOffset = CGPointMake(offset * scrollView.bounds.size.width, 0);
    }
    
}

@end
